package com.ai.mall.service.impl;

import com.ai.mall.dao.FlashSalesDao;
import com.ai.mall.dao.ProductImagesDao;
import com.ai.mall.dao.ProductRecommendationsDao;
import com.ai.mall.dao.ProductsDao;
import com.ai.mall.entity.*;
import com.ai.mall.service.ProductsService;
import com.ai.mall.utils.PageUtils;
import com.ai.mall.utils.Query;
import com.ai.mall.utils.R;
import com.ai.mall.vo.res.SeckillProductVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;


@Service("productsService")
public class ProductsServiceImpl extends ServiceImpl<ProductsDao, ProductsEntity> implements ProductsService {

    @Autowired
    private ProductsDao productsDao;
    @Autowired
    private FlashSalesDao flashSalesDao;
    @Autowired
    private ProductImagesDao productImagesDao;
    @Autowired
    private ProductRecommendationsDao productRecommendationsDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ProductsEntity> page = this.page(
                new Query<ProductsEntity>().getPage(params),
                new QueryWrapper<ProductsEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<ProductsEntity> searchByKeyword(String keyword) {
        if (StringUtils.isBlank(keyword)) {
            return Collections.emptyList();
        }
        QueryWrapper<ProductsEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("product_name", keyword);
        return getBaseMapper().selectList(queryWrapper);
    }

    @Override
    public List<ProductsEntity> getSelfOperatedPhones() {
        QueryWrapper<ProductsEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category_id", 1);
        return getBaseMapper().selectList(queryWrapper);
    }

    @Override
    public List<ProductsEntity> getEarphoneAccessories() {
        QueryWrapper<ProductsEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category_id", 2);
        return getBaseMapper().selectList(queryWrapper);
    }

    @Override
    public List<ProductsEntity> getTablets() {
        QueryWrapper<ProductsEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category_id", 3);
        return getBaseMapper().selectList(queryWrapper);
    }

    @Override
    public List<SeckillProductVO> getSeckillProducts() {
        // 查询秒杀活动
        Date time = Calendar.getInstance().getTime();
        QueryWrapper<FlashSalesEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lt("start_time", time);
        queryWrapper.gt("end_time", time);
        List<FlashSalesEntity> flashSales = flashSalesDao.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(flashSales)) {
            return Collections.emptyList();
        }

        Map<Integer, FlashSalesEntity> FlashSalesMap = flashSales.stream().collect(Collectors.toMap(FlashSalesEntity::getProductId, obj -> obj, (k1, k2) -> k1));


        // 提取商品id
        List<Integer> productIds = flashSales.stream()
                .map(FlashSalesEntity::getProductId)
                .collect(Collectors.toList());

        List<ProductsEntity> productsEntities = productsDao.selectBatchIds(productIds);

        // 组装成SeckillProductVO对象
        List<SeckillProductVO> seckillProductVOS = new ArrayList<>();
        for (ProductsEntity productsEntity : productsEntities) {
            SeckillProductVO vo = new SeckillProductVO();
            BeanUtils.copyProperties(productsEntity, vo);
            FlashSalesEntity flashSalesEntity = FlashSalesMap.get(productsEntity.getProductId());
            if (flashSalesEntity != null) {
                vo.setSeckillPrice(flashSalesEntity.getSalePrice());
                vo.setSaleStock(flashSalesEntity.getSaleStock());
                vo.setStartTime(flashSalesEntity.getStartTime());
                vo.setEndTime(flashSalesEntity.getEndTime());
            }

            // 查询商品图片
            ProductImagesEntity productImagesEntity = productImagesDao.selectOne(new QueryWrapper<ProductImagesEntity>()
                    .eq("product_id", productsEntity.getProductId())
                    .eq("is_primary", 1));

            if (productImagesEntity != null) {
                vo.setImageUrl(productImagesEntity.getImageUrl());
            }
            seckillProductVOS.add(vo);
        }
        return seckillProductVOS;
    }

    @Override
    public List<ProductsEntity> getRecommendedProducts(UsersEntity userInfo) {
        List<ProductRecommendationsEntity> recommendationsEntityList = productRecommendationsDao.selectList(new QueryWrapper<ProductRecommendationsEntity>()
                .eq("user_id", userInfo.getUserId()));
        if (CollectionUtils.isEmpty(recommendationsEntityList)) {
            return Collections.emptyList();
        }
        List<Integer> productIds = recommendationsEntityList.stream()
                .map(ProductRecommendationsEntity::getProductId)
                .collect(Collectors.toList());
        List<ProductsEntity> productsEntities = productsDao.selectBatchIds(productIds);
        return productsEntities;
    }
}